AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")

include("shared.lua")

module("Game", package.seeall )

CurrentGameState = nil

hook.Add("PlayerInitialSpawn", "StartGame", function()

	StartGame()
	
	hook.Remove("PlayerInitialSpawn", "StartGame")
	
end )

hook.Add("PlayerDisconnected", "RestartServer", function()

	timer.Simple( 10.0, function()
		
		if #player.GetAll() == 0 then
			game.LoadNextMap()
		end
	
	end )

end )

hook.Add("Think", "CheckGameState", function()

	if Game.TimeLeft() <= 0 then
		Game.StartNext()
	end
	
end )

function StartGame()
	StartBuild()
end


function RestartTimer()
	RunConsoleCommand("nc_roundstart", CurTime() )
end

function StartNext()

	local ActiveState = State()
	
	if ActiveState == FIGHT then
		StartBuild()
	
	elseif ActiveState == BUILD then
	
		//Increase game level by 1
		local NextRound = Round() + 1
			
		if NextRound > MaxRound() then //Game has ended
				
			StartScoreboard()
			return
			
		end
		
		StartFight()
		RunConsoleCommand("nc_round", NextRound )
	
	elseif ActiveState == SCOREBOARD then
		
		RunConsoleCommand("changelevel", "sf_skywalk")
		
	end
	
end

function SetState( state )
	CurrentGameState = state
	RunConsoleCommand("nc_gamestate", state )
	hook.Call("StateChange", GAMEMODE, state )
	
	umsg.Start("SFGame", nil )
		umsg.Char( 0 )
		umsg.Long( state )
	umsg.End()
end

function RespawnPlayers()
		
	for _, ply in pairs( player.GetAll() ) do
		ply:StripWeapons()
		ply:Spawn()
	end
	
end	

function StartScoreboard()
	
	umsg.Start("SFGame", nil )
		umsg.Char( 1 )
	umsg.End()
	
	SetState( SCOREBOARD )
	RestartTimer()
	
	for _, ply in pairs( player.GetAll() ) do
		ply:StripWeapons()
	end

end

function StartFight()
	
	SetState( FIGHT )
	RestartTimer()
	RespawnPlayers()
	
end

function StartBuild()
	
	SetState( BUILD )
	RestartTimer()
	RespawnPlayers()
	
end

concommand.Add("nc_nextround", function( ply )
	if ply == NULL || ply:IsAdmin() then
		StartNext()
	end
end )